package com.open.anim.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.open.anim.AnimModule;

import java.lang.reflect.InvocationTargetException;

/**
 * 工具类
 *
 * @Author: hailong.qiu 356752238@qq.com
 * @Maintainer: hailong.qiu 356752238@qq.com
 * @Date: 19-03-15
 * @Copyright: 2019 www.andriodtvdev.com Inc. All rights reserved.
 */
public class AnimUtils {

    public final static String OPEN_ANIM_MODULE_VALUE = "AnimModule";

    /**
     * 获取 AndroidManifest 的 全局配置类
     * <meta-data
     *      android:name="AnimModule"
     *      android:value="com.open.tvwidget.TestAnimModule" />
     *
     * @param context
     * @return
     */
    public static AnimModule getMetaData(final Context context) {
        try {
            ApplicationInfo ai = context.getPackageManager()
                                        .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai && null != ai.metaData) {
                String classPath = ai.metaData.getString(OPEN_ANIM_MODULE_VALUE);
                if (!TextUtils.isEmpty(classPath)) {
                    return parseModule(classPath);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static AnimModule parseModule(String className) {
        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unable to find GlideModule implementation", e);
        }

        Object module = null;
        try {
            module = clazz.getDeclaredConstructor().newInstance();
            // These can't be combined until API minimum is 19.
        } catch (InstantiationException e) {
            throwInstantiateGlideModuleException(clazz, e);
        } catch (IllegalAccessException e) {
            throwInstantiateGlideModuleException(clazz, e);
        } catch (NoSuchMethodException e) {
            throwInstantiateGlideModuleException(clazz, e);
        } catch (InvocationTargetException e) {
            throwInstantiateGlideModuleException(clazz, e);
        }

        if (!(module instanceof AnimModule)) {
            throw new RuntimeException("Expected instanceof GlideModule, but found: " + module);
        }
        return (AnimModule) module;
    }

    private static void throwInstantiateGlideModuleException(Class<?> clazz, Exception e) {
        throw new RuntimeException("Unable to instantiate GlideModule implementation for " + clazz, e);
    }

}
